/*
* name;
*/

class Matter_getStart{

	private Matter:any = Browser.window.Matter;
	private LayaRender:any = Browser.window.LayaRender;
	private stageWidth:number = 800;
	private stageHeight:number = 600;
    private engine:any;
    private player:any;
    private vx:number = 0;
    private vy:number = 0;
    private labelT:any;
    private PT:PlayTeeter;

    constructor(playTeeter:PlayTeeter){
        //Laya.init(this.stageWidth, this.stageHeight);
        //Laya.stage.alignV = Stage.ALIGN_MIDDLE;
        //Laya.stage.alignH = Stage.ALIGN_CENTER;
        //Laya.stage.scaleMode = "showall";

        this.PT = playTeeter;
        this.setup();
        // 监视加速器状态
		Accelerator.instance.on(Laya.Event.CHANGE, this, this.monitorAccelerator);
        // 游戏循环
		Laya.timer.frameLoop(1, this, this.animate);
    }

    private setup():void
    {
        this.initMatter();
        this.initWorld();

        //var ground2:any = Matter.Bodies.rectangle(610, 250, 200, 20, {isStatic: true, render: {fillStyle: '#edc51e', strokeStyle: '#b5a91c'}});
    }
    
	private monitorAccelerator(acceleration:AccelerationInfo, accelerationIncludingGravity:AccelerationInfo, rotationRate:Object, interval:Number):void
	{
		this.vx = accelerationIncludingGravity.x;
		this.vy = accelerationIncludingGravity.y;
	}

    private initMatter():void{
		var gameWorld:Sprite = new Sprite();
        var labelA:Text = new Text();
        labelA.textContent = "sadajhdsahd";
        this.labelT = labelA;
        //gameWorld.addChildren(labelA);

		Laya.stage.addChild(gameWorld);
        //Laya.stage.addChild(labelA);
        //this.labelT.text = "111";
        // 初始化物理引擎
        console.log("初始化物理引擎")
        this.engine = this.Matter.Engine.create({enableSleeping: true});
        this.Matter.Engine.run(this.engine);
        //渲染
        var render = this.LayaRender.create({engine: this.engine, width: 1300, height: 768, options: {background: '../bin/res/background.png', wireframes: false}});
		this.LayaRender.run(render);
    }

    private initWorld():void{

        //去除重力
        this.engine.world.gravity.y = 0;

        //创建静态的碰撞区域
        let mapJson = JsonManager.Instance(JsonManager).jsonDic['map1'];
        this.analysisMap(mapJson);
        
        //四个边
        var upSide:any = this.Matter.Bodies.rectangle(650, 5, 1300, 10, {isStatic: true, render: {fillStyle: '#edc51e', strokeStyle: '#b5a91c'}});
        var downSide:any = this.Matter.Bodies.rectangle(650, 768, 1300, 10, {isStatic: true, render: {fillStyle: '#edc51e', strokeStyle: '#b5a91c'}});
        var leftSide:any = this.Matter.Bodies.rectangle(5, 384, 10, 768, {isStatic: true, render: {fillStyle: '#edc51e', strokeStyle: '#b5a91c'}});
        var rightSide:any = this.Matter.Bodies.rectangle(1300, 384, 10, 768, {isStatic: true, render: {fillStyle: '#edc51e', strokeStyle: '#b5a91c'}});
        /*
        //柱子
        var side1:any = this.Matter.Bodies.rectangle(325, 480, 10, 576, {isStatic: true, render: {fillStyle: '#edc51e', strokeStyle: '#b5a91c'}});
        var side2:any = this.Matter.Bodies.rectangle(650, 288, 10, 576, {isStatic: true, render: {fillStyle: '#edc51e', strokeStyle: '#b5a91c'}});
        var side3:any = this.Matter.Bodies.rectangle(975, 480, 10, 576, {isStatic: true, render: {fillStyle: '#edc51e', strokeStyle: '#b5a91c'}});
        //坑
        var hole1:any = this.Matter.Bodies.circle(250, 150, 30, {isStatic: true, render: {fillStyle: '#edc51e', strokeStyle: '#b5a91c'}});
        //终点
        var des:any = this.Matter.Bodies.circle(1100, 700, 30, {label:"des", isStatic: true, render: {fillStyle: '#ff0000', strokeStyle: '#b5a91c'}});
        */

        //玩家
        var rockOptions:any = {density: 0.001, render: {sprite: {texture: '../bin/res/rock.png', xOffset: 23.5, yOffset: 23.5}}};
        var rock:any = this.Matter.Bodies.polygon(100, 100, 8, 20, rockOptions)
        this.player = rock;

        //添加到世界中
        //this.Matter.World.add(this.engine.world, [upSide, downSide, leftSide, rightSide, des, side1, side2, side3, hole1, rock]);
        this.Matter.World.add(this.engine.world, [upSide, downSide, leftSide, rightSide, rock]);

        //按键控制
        let pressKey: any = {};
        Laya.stage.on(Laya.Event.KEY_DOWN, this, (event: Laya.Event) => {
            //console.log("按键按下"+event.keyCode);
            pressKey[event.keyCode] = true;
        });
        Laya.stage.on(Laya.Event.KEY_UP, this, (event: Laya.Event) => {
            //console.log("按键松开"+event.keyCode);
            delete pressKey[event.keyCode];
        });
        //自定义事件
        Laya.stage.on("hit", this, (event: Laya.Event) => {
            this.hitHole();
        });

        let position = this.Matter.Vector.create(0, 0);
        

        //类似于unity的那个update函数
        this.Matter.Events.on(this.engine, 'beforeUpdate', () => {
            //console.log('beforeUpdate');
            //一直在运行

            //根据按建赋速度
            let x = 0, y = 0;
            //按左键和右键
            if (pressKey[Laya.Keyboard.LEFT]) {
                x = -10;
            } else if (pressKey[Laya.Keyboard.RIGHT]) {
                x = 10;
            }
            //按上下键
            if (pressKey[Laya.Keyboard.UP]) {
                y = -10;
            } else if (pressKey[Laya.Keyboard.DOWN]) {
                y = 10;
            }
            //按空格键
            /*
            if (pressKey[Laya.Keyboard.SPACE] && Math.abs(rock.velocity.y) <= 0.001) {
                y = -10;
            }
            */
            if (pressKey[Laya.Keyboard.SPACE]) {
                console.log("空格")
                //归位
                this.Matter.Body.setPosition(rock, this.Matter.Vector.create(100, 100));
            }
            
            if (x || y) {
                x = x || rock.velocity.x;
                y = y || rock.velocity.y;
                //console.log('x' + x + 'y' + y);
                //给物体赋值速度
                //this.Matter.Body.setVelocity(rock, { x: x, y: y });

                //采用键盘方向键给物体添加力
                //给物体施加力(要除以这么多，应该是物体太轻了，加些密度和质量)
                //let force = this.Matter.Vector.create(x/10000, y/10000);
                //this.Matter.Body.applyForce(rock, rock.position, force);
            }

            //采用手机重力给物体添加力(这个是调用了另外一个类，其实自己也能实现，具体代码在下面)
            //let force = this.Matter.Vector.create(this.PT.vy/10000, -this.PT.vx/10000);
            //this.Matter.Body.applyForce(rock, rock.position, force);

            //碰撞检测(按照飞机大战那种算距离的方式来检测碰撞，同时Matter也提供了碰撞)
            
        });

        //Matter提供的碰撞(另外一种写法https://blog.csdn.net/honey199396/article/details/79585613)
        this.Matter.Events.on(this.engine, 'collisionStart', function(e) {
            var i, pair,
                length = e.pairs.length;
            console.log(length);
            for(i = 0; i < length; i++) {
                pair = e.pairs[i];
                console.log("A:  " + pair.bodyA.label);
                console.log("B:  " + pair.bodyB.label);
                if(pair.bodyA.label == "Circle Body"){
                    //这个地方不能调用其他方法
                    //this.hitHole();
                    console.log("撞上了");
                    //用事件
                    Laya.stage.event("hit");
                }
                else if(pair.bodyA.label == "des"){
                    console.log("到达终点")
                }
            }
        });
        
        //this.Matter.Events.on(this.engine, 'collisionStart', this.hitHole);
    }

    //撞坑了
    private hitHole():void{
        console.log("撞上了");
        //归位
        this.Matter.Body.setPosition(this.player, this.Matter.Vector.create(100, 100));
    }

    private animate():void{
        this.PT.text_label.text = "v2hahaha" + this.vx + "   " + this.vy;
        //console.log(this.vx)
        let force = this.Matter.Vector.create(this.vy/10000, -this.vx/10000);
        this.Matter.Body.applyForce(this.player, this.player.position, force);
    }

    //解析地图数据
    public analysisMap(mapJson:any):void{
        console.log("解析地图");
        let x = mapJson[1];
        console.log(x);
        let y = x['Type'];
        console.log(y);
        console.log("长度");
        console.log(mapJson.length)
        console.log(typeof(mapJson))

        console.log("循环");
        for(let k in mapJson){
            console.log("键" + k)
            let v = mapJson[k];
            console.log(v);
            let type = v['Type'];
            console.log(type)
            //Matter.World.add(engine.world, [rock]);
            switch (type){
                case 'side':{
                    this.Matter.World.add(this.engine.world, [this.createSide(v)]);
                    break;
                }
                case 'hole':{
                    this.Matter.World.add(this.engine.world, [this.createHole(v)]);
                    break;
                }
                case 'des':{
                    this.Matter.World.add(this.engine.world, [this.createDes(v)]);
                    break;
                }
            }
        }
    }

    //创造边
    createSide(v:any):void {
        console.log("创建边")
        return this.Matter.Bodies.rectangle(v['num1'], v['num2'], v['num3'], v['num4'], {isStatic: true, render: {fillStyle: '#edc51e', strokeStyle: '#b5a91c'}});
    }

    //创造坑
    createHole(v:any):void {
        console.log("创建坑")
        return this.Matter.Bodies.circle(v['num1'], v['num2'], v['num3'], {isStatic: true, render: {fillStyle: '#edc51e', strokeStyle: '#b5a91c'}});
    }

    //创造终点
    createDes(v:any):void {
        console.log("创建终点")
        return this.Matter.Bodies.circle(v['num1'], v['num2'], v['num3'], {label:"des", isStatic: true, render: {fillStyle: '#ff0000', strokeStyle: '#b5a91c'}});
    }
}